package com.jishuo.nontax.bfc.service;

import com.github.pagehelper.PageHelper;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.service.SequenceService;
import com.jishuo.base.util.ExportSXSSFUtil;
import com.jishuo.nontax.bean.vo.BankBalanceVO;
import com.jishuo.nontax.bean.vo.BankVO;
import com.jishuo.nontax.bfc.dao.BankBalanceMapper;
import com.jishuo.nontax.bfc.dao.BankMapper;
import com.jishuo.nontax.bfc.dao.PreerrMapper;
import com.jishuo.nontax.bfc.pzk.PzkService;
import com.jishuo.nontax.bfc.tlq.MessageFactory;
import com.jishuo.nontax.bfc.tlq.MessageService;
import com.jishuo.nontax.util.PzkUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @auther dinggaofei
 * @Date 2022/12/20 14:31
 */
@Service
public class BankBalanceService {

    private static Logger logger = LoggerFactory.getLogger(BankBalanceService.class);

    @Resource
    private BankBalanceMapper bankBalanceMapper;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private MessageService messageService;
    @Resource
    private PreerrMapper preerrMapper;
    @Resource
    private PzkService pzkService;
    @Resource
    private PzkUtils pzkUtils;

    /**
     * 获得余额列表
     * @return
     */
    public List<BankBalanceVO> findBankBalancePage(BankBalanceVO bankBalanceVO, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return bankBalanceMapper.findBankBalancePage(bankBalanceVO);
    }

    /**
     * 增加余额，web
     * @param bankBalanceVO
     * @return
     */
    public BaseResult insertBankBalance(BankBalanceVO bankBalanceVO) {
        if (bankBalanceMapper.findBankBalance(Long.parseLong(bankBalanceVO.getBankid()), bankBalanceVO.getAccountdate()).size() > 0) {
            new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), bankBalanceVO.getAccountdate() + "余额已存在");
        }
        String wtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        bankBalanceVO.setWritedate(wtime);
        if(bankBalanceMapper.insertBankBalance(bankBalanceVO)>0){
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.DB_ERR);
    }

    /** 更新余额 */
    public BaseResult updateBankBalance(BankBalanceVO bankBalanceVO){
        if(bankBalanceMapper.updateBankBalance(bankBalanceVO)>0){
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.DB_ERR);
    }

    /** 删除余额 */
    public BaseResult deleteBankBalance(int bankid, String accountDate) {
        bankBalanceMapper.deleteBankBalanceDate(bankid, accountDate);
        return new BaseResult();
    }


    /**
     * 新增或更新账户，api使用
     * @param
     * @auther dinggaofei
     * @Date 2022/12/20 14:40
     * @description 记录账户余额信息
     */
    public BaseResult setBankBalance(BankBalanceVO bal) {
        if (bal.getAccountdate().length() != 10) return new BaseResult(ErrorCodeEnum.PARAM_ERR);
        BankVO bank = bankMapper.findBankVO(bal.getAccountcode());
        if (bank == null) return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "账户不存在");
        bal.setBankid(String.valueOf(bank.getBankid()));
        int ret = 0;
        if (bankBalanceMapper.findBankBalance(bank.getBankid(), bal.getAccountdate()).size() > 0) {
            // 更新
            ret = bankBalanceMapper.updateBankBalance(bal);
        } else {
            String wtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            bal.setWritedate(wtime);
            ret = bankBalanceMapper.insertBankBalance(bal);
        }
        return (ret > 0) ? new BaseResult() : new BaseResult(ErrorCodeEnum.DB_ERR);
    }

    /**
     * 发送财政
     * @param bankid 账号id
     * @param accountdate 日期
     * @return
     */
    public BaseResult sendBankBalance(long bankid,String accountdate, boolean chkPreResult) {
        // 检测是否预审成功 （查询t_fspreresults表中是否存在数据）
        if (chkPreResult && preerrMapper.preCheckSuc(bankid, accountdate) <= 0) return BaseResult.CustomErr("预审失败，不允许发送余额");
        accountdate = accountdate.substring(0,10);
        return this.sendBankBalance(bankBalanceMapper.findBankBalance(bankid, accountdate));
    }

    /**
     * 对账流水发送财政
     * @param accountcode 账号
     * @param accountdate 日期
     * @return
     */
    public BaseResult sendBankBalance(String accountcode, String accountdate) {
        BankVO bank = bankMapper.findBankVO(accountcode);
        if (bank == null) return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "账户不存在");
        return this.sendBankBalance(bank.getBankid(), accountdate, false);
    }

    private BaseResult sendBankBalance(List<BankBalanceVO> list) {
        try {
            if (list.size() == 0) return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "余额数据不存在");
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            //发送到财政
            Object bankBalance = MessageFactory.getBankBalance(list);
            messageService.sendMessage("SETBANKBALANCE", messageid, bankBalance, "2.0");
            // 写凭证
            pzkService.savePzmsg("SETBANKBALANCEPZK", pzkUtils.getBankBalance(list));
            return new BaseResult();
        } catch (Exception e) {
            logger.info("发送余额错误。", e);
            return new BaseResult(ErrorCodeEnum.SYS_ERR);
        }
    }

    public void findBankBalanceExport(BankBalanceVO bankBalanceVO, HttpServletResponse response) throws IOException {
        List<BankBalanceVO> list = bankBalanceMapper.findBankBalancePage(bankBalanceVO);
        String[] headers = {"银行id","余额","日期","开户行","账户","账号","是否发送","messageid","写入日期"};
        //数据键名或者MODEL类字段名
        String[] col = {"bankid","fund","accountdate","bankname","accountname","accountcode","issend","messageid","writedate"};
        ExportSXSSFUtil ex = new ExportSXSSFUtil();
        SXSSFWorkbook workbook = ex.exportExcelSXSSF("账户余额列表", headers, col, list, null);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("账户余额列表.xls").getBytes(), "iso-8859-1"));
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }


}
